package cn.iune.erp.inventory;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.erp.core.BusinessService;

@Transactional
@Service
public class StorageRecordServiceImpl implements IStorageRecordService {
	private final Logger log = LogManager.getLogger(this);

	@Autowired
	private IStorageRecordDao dao;
	@Autowired
	private IStorageRecordDetailDao detailDao;
	

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#getAll()
	 */
	@Override
	public List<StorageRecord> getAll(){
		return dao.getAll();
	}
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#getByID(java.lang.String)
	 */
	@Override
	public StorageRecord getByID(String fID) {
		return dao.getByID(fID);
	}
	
	@Transactional
	@Override
	public void insert(StorageRecord obj) {
		dao.insert(obj);
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#delete(java.lang.String)
	 */
	@Transactional
	@Override
	public void delete(String fID) {
		dao.delete(fID);
	}

	@Transactional
	@Override
	public void update(StorageRecord obj) {
		dao.update(obj);
	}

	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#getByNo(java.lang.String, java.lang.String)
	 */
	@Override
	public StorageRecord getByNo(String recordNo, String enterpriseNo) {
		return dao.getByNo(recordNo, enterpriseNo);
	}
	
	@Override
	public StorageRecord getByOriginNo(String origin, String originNo, String enterpriseNo) {
		return dao.getByOriginNo(origin, originNo, enterpriseNo);
	}

	@Transactional
	@Override
	public JSONObject save(JSONObject object) throws ParseException {
		//System.out.println("StorageRecord.save-->"+object.toJSONString());
		/*
		//判断数据（日期型数据是否合格）
		String relationAlias = object.getJSONObject("userdata").getString("relationAlias");
		String relationTypes = object.getJSONObject("userdata").getString("relationTypes");
		System.out.println("StorageRecord.save.relationAlias-->"+relationAlias);
		System.out.println("StorageRecord.save.relationTypes-->"+relationTypes);
		
		String[] cols = relationAlias.split(",");
		String[] types = relationTypes.split(",");
		
		JSONArray data = object.getJSONArray("rows");
		//循环行
		System.out.println("**********行数"+data.size());
		for(int index=0;index<data.size();index++) {
			JSONObject row = data.getJSONObject(index);
			System.out.println("**********"+row.toJSONString());
			//循环列
			for(int i=0;i<cols.length;i++) {
				String type = types[i];
				if("Date".equals(type) || "DateTime".equals(type)) {
					String col = cols[i];
					JSONObject cvalue = row.getJSONObject(col);
					System.out.println("type-->>"+type+"-->>column-->>"+col+"-->>value-->>"+cvalue.get("value"));
					System.out.println("type-->>"+type+"-->>column-->>"+col+"-->>value-->>"+cvalue.get("originalValue"));
				}
			}
		}
		*/
		
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject json = new JSONObject();
		json.put("concept", "StorageRecord");
		JSONArray rows = new JSONArray();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			StorageRecord obj = JSON.toJavaObject(javaObject, StorageRecord.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				StorageRecord objNew = dao.update(obj);
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
			}
		}
		
		json.put("rows", rows);
		
		return json;
	}
	
	@Transactional
	@Override
	public JSONObject saveDetail(JSONObject object) throws ParseException {
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject json = new JSONObject();
		json.put("concept", "StorageRecordDetail");
		JSONArray rows = new JSONArray();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			StorageRecordDetail obj = JSON.toJavaObject(javaObject, StorageRecordDetail.class);
			if(RowState.NEW.equals(obj.getRowState())){
				detailDao.insert(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				detailDao.delete(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				StorageRecordDetail data = detailDao.update(obj);
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", data.getVersion());
				rows.add(jsonRow);
			}
		}
		
		json.put("rows", rows);
		
		return json;
	}

	
	
	
	///////////////////////业务功能///////////////////////////////////////
	
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#confirm(java.lang.String)
	 */
	@Transactional
	@Override
	public int confirm(String fID) {
		StorageRecord sr = dao.getByID(fID);
		sr.setState("confirm");
		sr.setResultStatus("审核中");
		dao.update(sr);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#active(java.lang.String)
	 */
	@Transactional
	@Override
	public int active(String fID) {
		StorageRecord sr = dao.getByID(fID);
		sr.setState("active");
		sr.setResultStatus("待审核");
		dao.update(sr);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#close(java.lang.String)
	 */
	@Transactional
	@Override
	public int close(String fID) {
		StorageRecord sr = dao.getByID(fID);
		sr.setStatus("close");
		dao.update(sr);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#open(java.lang.String)
	 */
	@Transactional
	@Override
	public int open(String fID) {
		StorageRecord sr = dao.getByID(fID);
		sr.setStatus("open");
		dao.update(sr);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#agreeIt(java.lang.String)
	 */
	@Transactional
	@Override
	public int agreeIt(String fID,String usercode,String username, String userId) {
		StorageRecord sr = dao.getByID(fID);
//		System.out.println("fID-->"+fID);
//		System.out.println("sr-->"+sr);

		sr.setAudit("confirm");
		sr.setConfirmDate(Utils.getCurrentDate());
		
		sr.settUsercode(usercode);
		sr.settUsername(username);
		sr.settDatetime(Utils.getCurrentDateTime());
		
		sr.setResultStatus("已审核");

		dao.update(sr);

		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#unAgree(java.lang.String)
	 */
	@Transactional
	@Override
	public int unAgree(String fID) {
		StorageRecord sr = dao.getByID(fID);
		//判断是否可以撤销
		
		sr.setAudit("active");
		sr.setConfirmDate(null);
		
		sr.settUsercode(null);
		sr.settUsername(null);
		sr.settDatetime(null);
		
		sr.setResultStatus("审核中");

		dao.update(sr);

		return 0;
	}

	
	//重新统计主表数量和金额
	@Transactional
	@Override
	public int calculateItemAmount(String fID){
		
		//重新计算主表金额
		//子表
		List<StorageRecordDetail> storageRecordDetailList = detailDao.getByMasterID(fID);
		BigDecimal itemAmount = BigDecimal.ZERO;
		BigDecimal orderAmount = BigDecimal.ZERO;
		BigDecimal orderAmountOld = BigDecimal.ZERO;
		BigDecimal orderAmountTax = BigDecimal.ZERO;
		BigDecimal orderAmountTotal = BigDecimal.ZERO;
		
		for(StorageRecordDetail obj :storageRecordDetailList){
			/*
			if(obj.getSttts()==0) {
				//不参加数量和金额的统计
				continue;
			}
			*/
			orderAmount = orderAmount.add(obj.getOrderAmount());
			orderAmountOld = orderAmountOld.add(obj.getOrderAmountOld());
			orderAmountTax = orderAmountTax.add(obj.getOrderAmountTax());
			orderAmountTotal = orderAmountTotal.add(obj.getOrderAmountTotal());
			
			if(obj.getCheckin()==0) {
				itemAmount = itemAmount.add(obj.getItemAmount());
			}
		}
		
		//主表
		StorageRecord storageRecord = dao.getByID(fID);

		//累计主表合计金额
		storageRecord.setOrderAmount(orderAmount);
		storageRecord.setOrderAmountOld(orderAmountOld);
		storageRecord.setOrderAmountTax(orderAmountTax);
		storageRecord.setOrderAmountTotal(orderAmountTotal);

		storageRecord.setItemAmount(itemAmount);

		//更新主表
		dao.update(storageRecord);
		return 0;
	}

	@Override
	public JSONObject querySimple(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject data = dao.querySimple(param);
			return data;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", "failure");
			
			return json;
		}
	}
	
	
	//更新明细表最大流水号
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#updateMaxDetailNo(java.lang.String, int)
	 */
	@Transactional
	@Override
	public int updateMaxDetailNo(String fID,int maxDetailNo){
		StorageRecord sr = dao.getByID(fID);
		sr.setMaxDetailNo(maxDetailNo);
		dao.update(sr);
		return 0;
	}
	
	//更新帐单号
	@Transactional
	@Override
	public int updateNextNo(String recordNo,String enterpriseNo, String next,String nextName
			,String nextNo
			){
		
//		System.out.println(accountInvoiceNo);
		StorageRecord sr = dao.getByNo(recordNo, enterpriseNo);
		if(sr!=null) {
			sr.setNext(next);
			sr.setNextName(nextName);
			sr.setNextNo(nextNo);
			
			if(nextNo!=null) {
				sr.setInvoiceStatus("invoiced");
				sr.setInvoiceStatusLabel("已开票");
			}else {
				sr.setInvoiceStatus("uninvoice");
				sr.setInvoiceStatusLabel("待开票");
			}
			
			dao.update(sr);
		}
		
		return 0;
	}


	/*
	//更新单据状态
	//已发货（更新为待收货状态）
	@Transactional
	@Override
	public int updateUnreceived(String fID) {

		StorageRecord so = dao.getByID(fID);
		so.setHandling("unreceived");
		so.setHandlingLabel("待收货");
		
		dao.update(so);
		return 0;
	}
	*/

	/*
	//更新单据状态
	//已完成
	@Transactional
	@Override
	public int updateFinished(String fID) {

		StorageRecord so = dao.getByID(fID);
		so.setHandling("finished");
		so.setHandlingLabel("已完成");
		
		dao.update(so);
		return 0;
	}
	*/
	
	//更新地址
	@Transactional
	@Override
	public int updateAddress(JSONObject data){
		//主表
		String fID = data.getString("id");
		
		StorageRecord storageRecord = dao.getByID(fID);
		//System.out.println("fID-->"+fID);
		
		if(storageRecord==null){
//			jsonobject.put("code", -1);
//			jsonobject.put("status", "订单主表不存在，请检查是否传入ID有误！");
			return -1;
		}
		
//		String cUsercode = data.getString("personCode");
//		String cUsername = data.getString("personName");
//		String userId = data.getString("personID");
		
		JSONObject address = data.getJSONObject("addressRow");
		
		String fAddressID = address.getString("fID");
		String fAddressName = address.getString("fAddressName");
		String fAddress = address.getString("fAddress");
		String fAddressDetail = address.getString("fAddressDetail");
		String contacts = address.getString("contacts");
		String mobilePhone = address.getString("mobilePhone");
		String fPhone = address.getString("fPhone");
		
		String fProvince = address.getString("fProvince");
		String fCity = address.getString("fCity");
		String fZone = address.getString("fZone");
		
		storageRecord.setfAddressID(fAddressID);
		storageRecord.setfAddressName(fAddressName);
		storageRecord.setfAddress(fAddress);
		storageRecord.setfAddressDetail(fAddressDetail);
		storageRecord.setContacts(contacts);
		storageRecord.setMobilePhone(mobilePhone);
		storageRecord.setfPhone(fPhone);
		
		storageRecord.setfProvince(fProvince);
		storageRecord.setfCity(fCity);
		storageRecord.setfZone(fZone);
		
		dao.update(storageRecord);
		
		return 0;
	}
	
	/*	
	//更新正在开票数量
	 (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#updateInvoiceItemQuantityIng(java.lang.String, java.math.BigDecimal)
	 
	@Transactional
	@Override
	public int updateInvoiceItemQuantityIng(
			String fID
			,BigDecimal invoiceQuantity
			){
		StorageRecord sr = dao.getByID(fID);
		sr.setInvoiceQuantityIng(sr.getInvoiceQuantityIng().add(invoiceQuantity));
		dao.update(sr);
		return 0;
	}
	//更新开票数量
	 (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#updateInvoiceItemQuantity(java.lang.String, java.math.BigDecimal, java.math.BigDecimal)
	 
	@Transactional
	@Override
	public int updateInvoiceItemQuantity(
			String fID
			,BigDecimal invoiceQuantity
			,BigDecimal invoiceAmount
			){
		StorageRecord sr = dao.getByID(fID);
		sr.setInvoiceQuantityIng(sr.getInvoiceQuantityIng().subtract(invoiceQuantity));
		sr.setInvoiceQuantity(sr.getInvoiceQuantity().add(invoiceQuantity));
		sr.setInvoiceAmount(sr.getInvoiceAmount().add(invoiceAmount));
		dao.update(sr);
		return 0;
	}
	//更新正在暂估数量
	 (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#updateEvaluateItemQuantityIng(java.lang.String, java.math.BigDecimal)
	 
	@Transactional
	@Override
	public int updateEvaluateItemQuantityIng(
			String fID
			,BigDecimal evaluateQuantity
			){
		StorageRecord sr = dao.getByID(fID);
		sr.setEvaluateQuantityIng(sr.getEvaluateQuantityIng().add(evaluateQuantity));
		dao.update(sr);
		return 0;
	}
	//更新暂估数量
	 (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#updateEvaluateItemQuantity(java.lang.String, java.math.BigDecimal, java.math.BigDecimal)
	 
	@Transactional
	@Override
	public int updateEvaluateItemQuantity(
			String fID
			,BigDecimal evaluateQuantity
			,BigDecimal evaluateAmount
			){
		StorageRecord sr = dao.getByID(fID);
		sr.setEvaluateQuantityIng(sr.getEvaluateQuantityIng().subtract(evaluateQuantity));
		sr.setEvaluateQuantity(sr.getEvaluateQuantity().add(evaluateQuantity));
		sr.setEvaluateAmount(sr.getEvaluateAmount().add(evaluateAmount));
		dao.update(sr);
		return 0;
	}
	//更新正在退货数量
	 (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#updateBackItemQuantityIng(java.lang.String, java.math.BigDecimal)
	 
	@Transactional
	@Override
	public int updateBackItemQuantityIng(
			String fID
			,BigDecimal itemQuantity
			){
		StorageRecord sr = dao.getByID(fID);
		sr.setBackItemIng(sr.getBackItemIng().add(itemQuantity));
		dao.update(sr);
		return 0;
	}
	//更新退货数量
	 (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageRecordService#updateBackItemQuantity(java.lang.String, java.math.BigDecimal, java.math.BigDecimal)
	 
	@Transactional
	@Override
	public int updateBackItemQuantity(
			String fID
			,BigDecimal itemQuantity
			,BigDecimal pieceQuantity
			){
		StorageRecord sr = dao.getByID(fID);
		sr.setBackItemIng(sr.getBackItemIng().subtract(itemQuantity));
		sr.setBackItemAmount(sr.getBackItemAmount().add(itemQuantity));
		sr.setBackPiece(sr.getBackPiece().add(pieceQuantity));
		dao.update(sr);
		return 0;
	}
 	*/
	
	@Override
	public StorageRecord packing(
			String billType
			,String billTypeName 
			,String systemCode 
			,int flowType 
			,String revOpay 
			,int direction 
			,int dealType
			,String costingCode 
			,String autoCode 
			,String origin 
			,String originName 
			,String billNo 

			,String cUsercode//=com.justep.system.context.ContextHelper.getOperator().getCode();
			,String cUsername//=com.justep.system.context.ContextHelper.getOperator().getName();
			,String userId //= com.justep.system.context.ContextHelper.getOperator().getID();
			,String enterpriseNo //= this.getEnterpriseNo();
			,String enterpriseName //= this.getEnterpriseName();
			){
		
		String APPID = null;
		if(billType.equals("XSCK")){
			APPID = "8afbf31f51d05a5ca5e5e3e59fd15e99";
		}
		if(billType.equals("XSRK")){
			APPID = "638bbc8d84d6dc6a9ed61d2f9c5ce163";
		}
		if(billType.equals("CGRK")){
			APPID = "154493d129a970fd5aaf035c49040d57";
		}
		if(billType.equals("CGCK")){
			APPID = "e1e167ffecef696b79e6c17fc9b82a9a";
		}
		
		if(billType.equals("SCRK")){
			APPID = "7b6d529b3e96d122a0e087b63afe3895";
		}
		if(billType.equals("SCCK")){
			APPID = "c3a1021844010d9a7b0d6367e1bdaa1e";
		}
		if(billType.equals("WWRK")){
			APPID = "704ce197f8502b03dc077c5c07aa84d8";
		}
		if(billType.equals("WWCK")){
			APPID = "241f422fd4ebeb2e03c4d3060dddb408";
		}
		
		if(billType.equals("SCFL") || billType.equals("WWFL")){
			APPID = "fb312876ed0984810120cc26a71fc340";
		}
		if(billType.equals("SCTL") || billType.equals("WWTL")){
			APPID = "50c7aa3657df4a2949a4c51d614d22ad";
		}

		StorageRecord obj = new StorageRecord();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		//单号
		/*
		Map<String,Object> map = usercenterService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
//		String systemCode = (String) map.get("systemCode");
		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
		String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
		String origin = (String) map.get("origin");
		String originName = (String) map.get("originName");
		if("Y".equals(autoCode)){
			String billNo = (String) map.get("billNo");
			obj.setRecordNo(billNo);
		}
		*/
		if("Y".equals(autoCode)){
			obj.setRecordNo(billNo);
		}
		
		obj.setBillType(billType);
		obj.setBillTypeName(billTypeName);
		obj.setSystemCode(APPID);
		obj.setFlowType(flowType);
		obj.setRevOpay(revOpay);
		obj.setDirection(direction);
		obj.setDealType(dealType);
		obj.setCostingCode(costingCode);
		obj.setOrigin(origin);
		obj.setOriginName(originName);
		
		obj.setState("active");
		obj.setStatus("open");
		obj.setAudit("active");
		obj.setOrderDate(Utils.getCurrentDate());
		
		obj.setcUsercode(cUsercode);
		obj.setcUsername(cUsername);
		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(userId);
		obj.setEnterpriseNo(enterpriseNo);
		obj.setEnterpriseName(enterpriseName);
		
		obj.setDetailsCount(0);
		obj.setDetailsCountState(0);
		obj.setMaxDetailNo(0);
		
		obj.setVersion(0);
		
		return obj;
	}
	
	
	
	
	@Override
	public JSONObject newData(JSONObject param) {
		return dao.create(param);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
//		String ucode = param.getString("ucode");
//		String uname = param.getString("uname");
//		String uid = param.getString("uid");
		
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			
			//首先删除子表
			List<StorageRecordDetail> srds = detailDao.getByMasterID(id);
			for(StorageRecordDetail srd:srds){
				detailDao.delete(srd.getfID());
			}

			//然后删除主表
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}
	
	@Override
	public JSONObject saveData(JSONObject param) {
		// TODO Auto-generated method stub
		JSONObject data;
		try {
			//保存主表
			data = this.save(param);
			
			//保存从表
			JSONArray slaves = param.getJSONArray("slaves");
			JSONObject slaveParam = slaves.getJSONObject(0);
			
			JSONObject slaveData = this.saveDetail(slaveParam);
			
			JSONArray slaveDatas = new JSONArray();
			slaveDatas.add(slaveData);
			data.put("slaves", slaveDatas);
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			log.info("ParseException开始打印：");
			e.printStackTrace();
			log.info("e.getMessage()-->>"+e.getMessage());
			log.info("ParseException完成打印。");
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	@Override
	public JSONObject queryData(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	
	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}

	//新增子表
	@Override
	public JSONObject newDataDetail(JSONObject param) {
		return detailDao.create(param);
	}
	
	//查询子表
	@Override
	public JSONObject queryDataDetail(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = detailDao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	
	
	//整单打折
	@Transactional
	@Override
	public JSONObject discountAmount(String fID, BigDecimal discountAmountTotal) {
		StorageRecord obj = dao.getByID(fID);
		return this.discountAmount(obj, discountAmountTotal);
	}
	
	//整单打折
	@Transactional
	@Override
	public JSONObject discountAmount(StorageRecord obj, BigDecimal discountAmountTotal) {
		JSONObject json = new JSONObject();
		
		List<StorageRecordDetail> storageRecordDetailList = detailDao.getByMasterID(obj.getfID());
		int taxType = obj.getTaxType();
		
		//含税：按orderAmount比例分配
		if(taxType==1 ||taxType==-1) {
			///////////////////////////////////////////////////
			BigDecimal orderAmountMaster = obj.getOrderAmount();
			////////////////////////////////////////////////////
			
			obj.setOrderAmount(BigDecimal.ZERO);
			obj.setOrderAmountOld(BigDecimal.ZERO);
			obj.setOrderAmountTax(BigDecimal.ZERO);
			obj.setOrderAmountTotal(BigDecimal.ZERO);
			
			if(orderAmountMaster.compareTo(BigDecimal.ZERO)==0) {
				//失败
				json.put("code", -1);
				json.put("msg", "failure");
				json.put("status", "失败，被除数为0！");
				return json;
			}
			for(StorageRecordDetail detail :storageRecordDetailList){
				
				////////////////////////////////////////////////
				BigDecimal orderAmount = detail.getOrderAmount();
				////////////////////////////////////////////////
				
				BigDecimal splitRate = orderAmount.divide(orderAmountMaster,10,RoundingMode.HALF_UP);
				
				////////////////////////////////////////////////////
				BigDecimal discountAmount = discountAmountTotal.multiply(splitRate).setScale(2,RoundingMode.HALF_UP);
				BigDecimal taxRate = detail.getTaxRate();
				/////////////////////////////////////////////////////
				
				detail.setDiscountAmount(discountAmount);
				//重新计税
				BigDecimal itemAmount = detail.getItemAmount();
				BigDecimal itemPrice = detail.getItemPrice();
				BigDecimal discountRate = detail.getDiscountRate();
	
				List<BigDecimal> taxList = BusinessService.taxCalculate(itemAmount, itemPrice, discountRate, discountAmount, taxType, taxRate);
				
				detail.setOrderAmount(taxList.get(0));
				detail.setOrderAmountOld(taxList.get(1));
				detail.setOrderAmountTax(taxList.get(2));
				detail.setOrderAmountTotal(taxList.get(3));
				
				obj.setOrderAmount(obj.getOrderAmount().add(detail.getOrderAmount()));
				obj.setOrderAmountOld(obj.getOrderAmountOld().add(detail.getOrderAmountOld()));
				obj.setOrderAmountTax(obj.getOrderAmountTax().add(detail.getOrderAmountTax()));
				obj.setOrderAmountTotal(obj.getOrderAmountTotal().add(detail.getOrderAmountTotal()));
				
		    	//storageRecordDetailService.update(detail);
			}			
		}
		
		//不含税：按orderAmountTotal比例分配
		if(taxType==0) {
			///////////////////////////////////////////////////
			BigDecimal orderAmountMaster = obj.getOrderAmountTotal();
			////////////////////////////////////////////////////
			
			obj.setOrderAmount(BigDecimal.ZERO);
			obj.setOrderAmountOld(BigDecimal.ZERO);
			obj.setOrderAmountTax(BigDecimal.ZERO);
			obj.setOrderAmountTotal(BigDecimal.ZERO);
	
			if(orderAmountMaster.compareTo(BigDecimal.ZERO)==0) {
				//失败
				json.put("code", -1);
				json.put("msg", "failure");
				json.put("status", "失败，被除数为0！");
				return json;
			}
			for(StorageRecordDetail detail :storageRecordDetailList){
				
				////////////////////////////////////////////////
				BigDecimal orderAmount = detail.getOrderAmountTotal();
				////////////////////////////////////////////////
				
				BigDecimal splitRate = orderAmount.divide(orderAmountMaster,10,RoundingMode.HALF_UP);
				
				//////////////////////////////////////////////////
				BigDecimal discountAmount = discountAmountTotal.multiply(splitRate);
				BigDecimal taxRate = detail.getTaxRate();
				discountAmount = discountAmount.divide(taxRate.add(BigDecimal.ONE),2,RoundingMode.HALF_UP);
				//////////////////////////////////////////////////
				
				detail.setDiscountAmount(discountAmount);
				//重新计税
				BigDecimal itemAmount = detail.getItemAmount();
				BigDecimal itemPrice = detail.getItemPrice();
				BigDecimal discountRate = detail.getDiscountRate();
	
				List<BigDecimal> taxList = BusinessService.taxCalculate(itemAmount, itemPrice, discountRate, discountAmount, taxType, taxRate);
				
				detail.setOrderAmount(taxList.get(0));
				detail.setOrderAmountOld(taxList.get(1));
				detail.setOrderAmountTax(taxList.get(2));
				detail.setOrderAmountTotal(taxList.get(3));
				
				obj.setOrderAmount(obj.getOrderAmount().add(detail.getOrderAmount()));
				obj.setOrderAmountOld(obj.getOrderAmountOld().add(detail.getOrderAmountOld()));
				obj.setOrderAmountTax(obj.getOrderAmountTax().add(detail.getOrderAmountTax()));
				obj.setOrderAmountTotal(obj.getOrderAmountTotal().add(detail.getOrderAmountTotal()));
				
		    	//storageRecordDetailService.update(detail);
			}			
		}
	
		for(StorageRecordDetail detail :storageRecordDetailList){
			detailDao.update(detail);
		}
		
		//主表
		obj.setDiscountAmount(discountAmountTotal);
		dao.update(obj);
		
		int rtn = 0;
		if(rtn==0) {
			//成功
			json.put("code", 0);
			json.put("msg", "success");
			json.put("status", "成功！");
			return json;
		}else {
			//失败
			json.put("code", -1);
			json.put("msg", "failure");
			json.put("status", "失败！");
			return json;
		}
	}
	

	
}
